package com.example.myapplication.fragment;

import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.example.myapplication.R;
import com.example.myapplication.events.TTSWorkingEvent;
import com.example.myapplication.model.Word;
import com.example.myapplication.tools.Preferences;
import com.example.myapplication.tools.SQLiteHelper;
import com.example.myapplication.tools.TTSHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;

public class WordFragment extends Fragment
        implements View.OnClickListener {

    private RadioGroup wordDB;
    private RadioButton btnCET6;
    private RadioButton btnTOEFL;
    private EditText startTv;
    private EditText endTv;
    private ImageView btnLeft;
    private ImageView btnRight;
    private TextView wordTv;
    private TextView translationTV;

    private Button btnSpeedAdd;
    private Button btnSpeedMinus;
    private Button btnDelayMinus;
    private Button btnDelayAdd;
    private TextView delayTv;
    private ImageView btnToggle;
    private TextView speedTv;

    private View mRootView;

    private int currIdx = 0;
    private boolean isPlaying = false;
    private int delay = 1000;

    private List<Word> wordList = new ArrayList<>();

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTTSWorking(TTSWorkingEvent event) {
        if(!isPlaying || event.type.equals("File"))
            return;
        updateWordView(0);

        btnToggle.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(currIdx == wordList.size()) {
                    setPlaying(false);
                    currIdx = 0;
                    updateWordView(0);
                } else if(currIdx < wordList.size() ) {
                    TTSHelper.getInstance().speak( wordList.get(currIdx).en );
                    currIdx++;
                }
            }
        }, delay);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        if(!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        mRootView = inflater.inflate(R.layout.fragment_word, container);

        wordDB = mRootView.findViewById(R.id.word_db);
        btnCET6 = mRootView.findViewById(R.id.cet6);
        btnTOEFL = mRootView.findViewById(R.id.toefl);
        startTv = mRootView.findViewById(R.id.idx_start);
        endTv = mRootView.findViewById(R.id.idx_end);

        btnToggle = mRootView.findViewById(R.id.toggle);

        btnLeft = mRootView.findViewById(R.id.btn_left);
        btnRight = mRootView.findViewById(R.id.btn_right);
        wordTv = mRootView.findViewById(R.id.word);
        translationTV = mRootView.findViewById(R.id.translation);

        btnSpeedAdd = mRootView.findViewById(R.id.btn_add_speed);
        btnSpeedMinus = mRootView.findViewById(R.id.btn_minus_speed);
        speedTv = mRootView.findViewById(R.id.speed);

        btnDelayMinus = mRootView.findViewById(R.id.btn_minus_delay);
        btnDelayAdd = mRootView.findViewById(R.id.btn_add_delay);
        delayTv = mRootView.findViewById(R.id.delay);

        delayTv.setText(delay+"");

        Button btnQuery = mRootView.findViewById(R.id.btn_query);
        Button btnSynth = mRootView.findViewById(R.id.btn_synth);
        btnSynth.setOnClickListener(this);
        btnQuery.setOnClickListener(this);
        btnLeft.setOnClickListener(this);
        btnRight.setOnClickListener(this);
        btnToggle.setOnClickListener(this);
        btnSpeedAdd.setOnClickListener(this);
        btnSpeedMinus.setOnClickListener(this);
        btnDelayAdd.setOnClickListener(this);
        btnDelayMinus.setOnClickListener(this);

        wordTv.setOnClickListener(this);
        translationTV.setOnClickListener(this);

        int db = Preferences.getInstance().loadWordDB();

        btnCET6.setChecked(db == 0);
        btnTOEFL.setChecked(db == 1);

        wordDB.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i) {
                    //保存用户的选择 持久化
                    case R.id.cet6:
                        Preferences.getInstance().saveWordDB(0);
                        break;
                    case R.id.toefl:
                        Preferences.getInstance().saveWordDB(1);
                        break;
                }
            }
        });


        int idx = Preferences.getInstance().loadIdxStart();
        startTv.setText(idx + "");
        idx = Preferences.getInstance().loadIdxEnd();
        endTv.setText(idx + "");

        startTv.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                String str = startTv.getText().toString();
                int start = Integer.parseInt(str);
                Preferences.getInstance().saveIdxStart(start);
            }
        });

        endTv.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                String str = endTv.getText().toString();
                int end = Integer.parseInt(str);
                Preferences.getInstance().saveIdxEnd(end);
            }
        });
        TTSHelper.getInstance();
        return mRootView;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onClick(View view) {
        if(view.getId() == R.id.btn_query) {
            updateWordList(0);
        } else if(view.getId() == R.id.btn_left) {
            updateWordView(-1);
        } else if(view.getId() == R.id.btn_right) {
            updateWordView(1);
        } else if (view.getId() == R.id.word) {
            setPlaying(false);
            TTSHelper.getInstance().speak(wordTv.getText().toString());
        } else if (view.getId() == R.id.btn_add_speed) {
            TTSHelper.getInstance().setSpeed(0.1f);
            speedTv.setText(    TTSHelper.getInstance().getSpeed()  );
        } else if (view.getId() == R.id.btn_minus_speed) {
            TTSHelper.getInstance().setSpeed(-0.1f);
            speedTv.setText(    TTSHelper.getInstance().getSpeed()  );
        } else if (view.getId() == R.id.toggle) {
            setPlaying(!isPlaying);
            if(isPlaying) {
                TTSHelper.getInstance().speak("");
            }
        } else if (view.getId() == R.id.btn_add_delay) {
            setDelay(200);
        } else if (view.getId() == R.id.btn_minus_delay) {
            setDelay(-200);
        } else if(view.getId() == R.id.btn_synth) {
            setPlaying(false);
            TTSHelper.getInstance().toFile(wordListToString());
        }
    }

    private String wordListToString() {
        String res = "";
        for (Word w: wordList) {
            res += w.en + ",";
        }
        return res;
    }

    private void setDelay(int d) {
        delay += d;
        delay = Math.min(5000, delay);
        delay = Math.max(200, delay);
        delayTv.setText(delay+"");
    }

    private void setPlaying(boolean what) {
        isPlaying = what;
        btnToggle.setBackground(  getResources().getDrawable(isPlaying ?  R.drawable.ic_pause : R.drawable.ic_play) );
    }

    private void updateWordView(int offset) {
        if(currIdx + offset >= 0 && currIdx + offset < wordList.size()) {
            currIdx += offset;
            wordTv.setText(wordList.get(currIdx).en);
            translationTV.setText(wordList.get(currIdx).getTranslation());
        }
    }

    private void updateWordList(int curr) {
        wordTv.setText("");
        translationTV.setText("");
        wordList.clear();
        String db = "CET6";
        db = Preferences.getInstance().loadWordDB() == 1 ? "TOEFL" : "CET6";
        int s = Integer.parseInt(startTv.getText().toString());
        int e = Integer.parseInt(endTv.getText().toString());
        wordList = SQLiteHelper.getInstance().query(db, s, e);
        currIdx = curr;
        if(wordList.size()>0) {
            updateWordView(0);
        }
    }
}
